package com.movie.ticketing.controller;

import com.movie.ticketing.client.UserServiceClient;
import com.movie.ticketing.entity.User;
import com.movie.ticketing.entity.UserResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserServiceClientController {

    @Autowired
    private UserServiceClient userServiceClient;

    @GetMapping("/user/{id}")
    public ResponseEntity<Map<String, Object>> getUserById(@PathVariable("id") Long id) {
        UserResponse<User> response = userServiceClient.getUserById(id);
        Map<String, Object> responseMap = new HashMap<>();

        if (response == null) {
            responseMap.put("code", 500);
            responseMap.put("message", "Service is currently unavailable");
            return ResponseEntity.status(500).body(responseMap);
        }

        if (response.getCode() == 200 && response.getData() != null) {
            responseMap.put("code", 200);
            responseMap.put("message", response.getMessage() != null ? response.getMessage() : "User retrieved successfully");
            responseMap.put("data", response.getData());
            return ResponseEntity.ok(responseMap);
        } else {
            responseMap.put("code", response.getCode());
            responseMap.put("message", response.getMessage() != null ? response.getMessage() : "Failed to retrieve user");
            return ResponseEntity.status(response.getCode()).body(responseMap);
        }
    }

    @GetMapping("/user")
    public ResponseEntity<Map<String, Object>> getAllUsers() {
        UserResponse<List<User>> response = userServiceClient.getAllUsers();
        Map<String, Object> responseMap = new HashMap<>();

        if (response == null) {
            responseMap.put("code", 500);
            responseMap.put("message", "Service is currently unavailable");
            return ResponseEntity.status(500).body(responseMap);
        }

        if (response.getCode() == 200 && response.getData() != null) {
            responseMap.put("code", 200);
            responseMap.put("message", response.getMessage() != null ? response.getMessage() : "All users retrieved successfully");
            responseMap.put("data", response.getData());
            return ResponseEntity.ok(responseMap);
        } else {
            responseMap.put("code", response.getCode());
            responseMap.put("message", response.getMessage() != null ? response.getMessage() : "Failed to retrieve users");
            return ResponseEntity.status(response.getCode()).body(responseMap);
        }
    }
}